CREATE TABLE `user`
(
    `id`        int(11) unsigned NOT NULL AUTO_INCREMENT,
    `user_name` varchar(32) DEFAULT NULL COMMENT '用户名称',
    `age`       int(11)     DEFAULT NULL COMMENT '年龄',
    `version`   int(11)     DEFAULT NULL COMMENT '版本',
    `sex`       int(11)     DEFAULT NULL COMMENT '性别 0-女 1-男',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8;

truncate table `user`;

INSERT INTO `user` (`user_name`, `age`, `version`, `sex`)
VALUES ('张三', 20, 1, 0),
       ('赵四', 30, 1, 1),
       ('王五', 40, 1, 1)
;

select * from user;

#悲观锁
begin;
select * from user where id = 1 for update ;
update user set user_name = '悲观锁1' where id = 1;
select * from user where id  = 1 ;
commit ;

# session2
update user set user_name = '悲观锁2' where id = 1;
update user set user_name = '赵思思' where id = 2;


# 乐观锁
update user set user_name = '悲观锁1',version = version + 1 where id = 1 and version = 1;
